package com.tarena.lbs.business.service.impl;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.business.dao.repository.StoreChainRepository;
import com.tarena.lbs.business.dao.repository.StoreRepository;
import com.tarena.lbs.business.pojo.param.StoreParam;
import com.tarena.lbs.business.pojo.po.StoreChainPO;
import com.tarena.lbs.business.pojo.po.StorePO;
import com.tarena.lbs.business.pojo.query.AreaStoreQuery;
import com.tarena.lbs.business.pojo.query.StoreQuery;
import com.tarena.lbs.business.pojo.vo.PictureVO;
import com.tarena.lbs.business.pojo.vo.StoreVO;
import com.tarena.lbs.business.service.StoreService;
import io.micrometer.common.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class StoreServiceImpl implements StoreService {
    @Autowired
    private StoreRepository storeRepository;
    @Autowired
    private StoreChainRepository chainRepository;


    @Override
    public List<StoreVO> getStoresByBusinessId(Integer businessId) {
        log.debug("根据商家ID查询店铺VO列表，入参：{}", businessId);
        List<StorePO> storePOs = storeRepository.findByBusinessId(businessId);
        if (CollectionUtils.isEmpty(storePOs)) {
            return Collections.emptyList();
        }

        // 将StorePO列表转换为StoreVO列表
        return storePOs.stream().map(po -> {
            StoreVO vo = new StoreVO();
            BeanUtils.copyProperties(po, vo);
            // 添加字段判空处理，设置默认值
            vo.setStoreName(vo.getStoreName() != null ? vo.getStoreName() : "");
            vo.setStoreHeadPhone(vo.getStoreHeadPhone() != null ? vo.getStoreHeadPhone() : "");
            return vo;
        }).collect(Collectors.toList());
    }

    @Override
    public PageResult<StoreVO> pageList(StoreQuery query) {
        log.debug("服务层分页查询店铺列表，入参：{}", query);
        // 调用Repository层的方法获取分页数据
        PageResult<StorePO> poPageResult = storeRepository.pageList(query);

        // 将StorePO列表转换为StoreVO列表
        List<StoreVO> voList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(poPageResult.getObjects())) {
            voList = poPageResult.getObjects().stream().map(po -> {
                StoreVO vo = new StoreVO();
                BeanUtils.copyProperties(po, vo);
                // 添加字段判空处理，设置默认值
                vo.setStoreName(vo.getStoreName() != null ? vo.getStoreName() : "");
                vo.setStoreHeadPhone(vo.getStoreHeadPhone() != null ? vo.getStoreHeadPhone() : "");
                return vo;
            }).collect(Collectors.toList());
        }

        // 构建返回结果
        PageResult<StoreVO> voPageResult = new PageResult<>();
        voPageResult.setObjects(voList);
        voPageResult.setTotal(poPageResult.getTotal());
        voPageResult.setPageNo(poPageResult.getPageNo());
        voPageResult.setPageSize(poPageResult.getPageSize());
        return voPageResult;
    }



    @Transactional
    @Override
    public void saves(StoreParam param) throws BusinessException {
        log.info("开始保存店铺数据，当前数据源: tarena_lbs_business");
        StorePO po = assembleBusinessPO(param);
        StorePO po1 = storeRepository.saveStore(po);
        log.info("店铺保存成功，ID: {}", po1.getId());

        //生成二維碼
        StoreChainPO cPo = new StoreChainPO();
        cPo.setStoreId(po1.getId());
        UUID uuid = UUID.randomUUID();
        String linke = "https://store.example.com/store?store=store"+uuid.toString().replace("-", "");
        cPo.setLink(linke);
        cPo.setLinkImage(po1.getStoreLogo());
        cPo.setLinkStatus(0);
        cPo.setBusinessId(po1.getBusinessId());
        cPo.setCreateTime(new Date());

log.info("准备保存店铺连锁信息到store_chain表，数据: {}", cPo);
try {
    chainRepository.saveStoreChain(cPo);
    log.info("店铺连锁信息保存成功");
} catch (Exception e) {
    log.error("保存店铺连锁信息失败: {}", e.getMessage(), e);
    throw new BusinessException("500", "保存店铺二维码信息失败: " + e.getMessage()); // 添加这行抛出异常
}


    }

    @Override
    public List<StoreVO> getStoreByCity(AreaStoreQuery query) {
        log.debug("根据区域查询店铺列表，入参：{}", query);

        // 验证参数
        if(query == null) {
            log.warn("区域查询参数为空");
            return Collections.emptyList();
        }

        List<StoreVO> vos = new ArrayList<>();  // 初始化为空列表而不是null
        List<StorePO> pos = storeRepository.getStoreByCity(query);

        if (CollectionUtils.isNotEmpty(pos)) {
            vos = pos.stream().map(po -> {
                StoreVO vo = new StoreVO();
                BeanUtils.copyProperties(po, vo);

                // 确保关键字段不为null
                vo.setStoreName(vo.getStoreName() != null ? vo.getStoreName() : "");
                vo.setStoreHeadPhone(vo.getStoreHeadPhone() != null ? vo.getStoreHeadPhone() : "");

                // 手动设置storeAddress数组，这是前端期望的格式
                try {
                    // 使用反射设置storeAddress属性，因为它在StoreVO类中未定义
                    List<String> storeAddress = new ArrayList<>();
                    if (vo.getProvinceId() != null) {
                        storeAddress.add(vo.getProvinceId().toString());
                    } else {
                        storeAddress.add("");
                    }
                    if (vo.getCityId() != null) {
                        storeAddress.add(vo.getCityId().toString());
                    } else {
                        storeAddress.add("");
                    }
                    if (vo.getAreaId() != null) {
                        storeAddress.add(vo.getAreaId().toString());
                    } else {
                        storeAddress.add("");
                    }

                    // 使用反射设置storeAddress属性
                    Field field = vo.getClass().getDeclaredField("storeAddress");
                    field.setAccessible(true);
                    field.set(vo, storeAddress);
                } catch (Exception e) {
                    log.warn("Failed to set storeAddress field: {}", e.getMessage());
                }

                return vo;
            }).collect(Collectors.toList());
        }

        log.debug("区域查询返回店铺数量：{}", vos.size());
        return vos;
    }

    @Override
    public void update(StoreParam param) {
        StorePO po = assembleBusinessPO(param);
        storeRepository.update(po);
    }

    @Override
    public StoreVO storeEdit(Integer storeId) {
        StorePO po = storeRepository.storeEdit(storeId);//id
        StoreVO vo =null;
        if(po!=null){
            vo = new StoreVO();
            BeanUtils.copyProperties(po, vo);
        }
        if(StringUtils.isNotEmpty(po.getStoreImagesId())){
            List<PictureVO> vos = new ArrayList<>();
            List <String> list = Arrays.asList(po.getStoreImagesId().split(","));
            for(String str:list){
                PictureVO pVo = new PictureVO();
                pVo.setId(1);
                pVo.setImage(str);
                vos.add(pVo);
            }
            vo.setPictureVOS(vos);
        }
        return vo;
    }

    @Override
    public List<StoreVO> getStoreById(AreaStoreQuery query) {
        log.debug("服务层根据ID列表查询店铺，入参：{}", query);

        // 验证参数
        if(query == null) {
            log.warn("查询参数为空");
            return Collections.emptyList();
        }

        List<StoreVO> vos = new ArrayList<>();
        List<StorePO> pos = storeRepository.getStoreById(query); // 调用正确的方法

        if (CollectionUtils.isNotEmpty(pos)) {
            vos = pos.stream().map(po -> {
                StoreVO vo = new StoreVO();
                BeanUtils.copyProperties(po, vo);

                // 确保关键字段不为null
                vo.setStoreName(vo.getStoreName() != null ? vo.getStoreName() : "");
                vo.setStoreHeadPhone(vo.getStoreHeadPhone() != null ? vo.getStoreHeadPhone() : "");

                return vo;
            }).collect(Collectors.toList());
        }

        log.debug("ID列表查询返回店铺数量：{}", vos.size());
        return vos;
    }

    @Override
    public void delete(Integer storeId) {
        //逻辑删除，将storeStatus设置为2
        StorePO po = storeRepository.storeEdit(storeId);
        //逻辑删除,检查店铺是否为空
        if(po!=null){
            po.setStoreStatus(2);
            storeRepository.update(po);
        }
        log.info("删除店铺成功,店铺ID:{}",storeId);
    }

    /**
     * 页面参数转换数据库实体类
     *
     * @param param
     * @return
     */
    private StorePO assembleBusinessPO(StoreParam param) {
        StorePO po = new StorePO();
        BeanUtils.copyProperties(param, po);
        // 手动设置坐标值，解决字段名称不匹配问题
        po.setStoreLongitude(param.getLongitude());
        po.setStoreLatitude(param.getLatitude());
        if(param.getId()==null){
            //创建时间
            po.setCreateTime(new Date());
        }
        po.setUpdateTime(new Date());
        // 为storeLogo设置默认值，防止数据库插入失败
        if (po.getStoreLogo() == null) {
            po.setStoreLogo("");
        }
        if (param.getStoreImagesIds()!=null && !param.getStoreImagesIds().isEmpty()) {
            List<String> ids = param.getStoreImagesIds();
            String images = ids.stream().collect(Collectors.joining(","));
            po.setStoreImagesId(images);
        }
        return po;
    }
}